import $service from '../service'

class Websocket {
  constructor({ heartCheck, isReconnection }) {
    this.init = false;
    this.isConnect = false;
    this.netWork = true;
    this.isClosed = false;
    this.timeout = 3000;
    this.timeoutObj = null;
    this.connectNum = 0;
    this.heartCheck = heartCheck;
    this.isReconnection = isReconnection;
    this.wsUrl = $service.wsUrl;
    this.socketTask = null;
    this.isInvited = false
    // 监听网络变化
    wx.onNetworkStatusChange((res) => {
      this.netWork = res.isConnected;
      if (!this.netWork) {
        this.isConnect = false;
        if (this.isReconnection) {
          this.reConnect();
        }
      }
    });

    this.initWebSocket();
  }

  initWebSocket(options = {}) {
    if (this.isConnect) {
      console.log("WebSocket已连接");
      return;
    }

    wx.getNetworkType({
      success: (res) => {
        if (res.networkType !== 'none') {
          this.connectSocket(options);
        } else {
          console.log('网络已断开');
          this.netWork = false;
        }
      }
    });
  }

  connectSocket(options = {}) {
    this.socketTask = wx.connectSocket({
      url: options.url || this.wsUrl,
      success: (res) => {
        console.log('WebSocket连接创建成功');
        options.success?.(res);
      },
      fail: (err) => {
        console.error('WebSocket连接创建失败', err);
        options.fail?.(err);
      }
    });

    this.initSocketListener();
  }

  initSocketListener() {
    if (!this.socketTask) return;

    this.socketTask.onOpen(() => {
      console.log('WebSocket连接已打开');
      this.isConnect = true;
      this.init = true;

      // 发送登录信息
      const loginData = JSON.stringify({
        token: wx.getStorageSync('miniToken'),
        packageType: 1
      });

      this.socketTask.send({
        data: loginData,
        success: () => {
          console.log('登录信息发送成功');
          if (this.heartCheck) {
            this.reset().start();
          }
        }
      });
    });

    this.socketTask.onClose((res) => {
      console.log('WebSocket连接已关闭:', res);
      this.isConnect = false;
      if (this.heartCheck) {
        this.reset();
      }
      if (!this.isClosed && this.isReconnection) {
        this.reConnect();
      }
    });

    this.socketTask.onError((err) => {
      console.error('WebSocket错误:', err);
      this.isConnect = false;
      if (!this.isClosed && this.isReconnection) {
        this.reConnect();
      }
    });
  }

  onReceivedMsg(callBack) {
    if (!this.socketTask) return;

    this.socketTask.onMessage(msg => {
      if (typeof callBack === "function") {
        if (typeof msg.data === 'object') {
          let unit8Arr = new Uint8Array(msg.data);
          let encodedString = String.fromCharCode.apply(null, unit8Arr);
          let decodedString = decodeURIComponent(escape((encodedString)));
          let res = JSON.parse(decodedString);
          callBack(res);

          // 处理特定类型的消息
          if (res.packageType === 7) {
            let userInfo = JSON.parse($service.getStore('userInfo'));
            let { inquiryType, doctorIM, id, doctorId, doctorName, patientIM } = res.inquiryPatientInfoResp;
            if (userInfo.type !== "D" && (inquiryType == 1 || inquiryType == 2)) {
              // 判断当前页面地址
              const pages=getCurrentPages();
              //获取当前页面实例
              const currentPage=pages[pages.length-1];
              //获取当前页面路径
              const currentPagePath=currentPage.route;

              if(currentPagePath==="pages/chat/user_chat/user_chat"){
                console.log("当前页面是会诊页");
                return
              }
              if (inquiryType == 1) {
                $service.setStore('tencentConfigP', JSON.stringify(res.tencentConfig));
                if (this.isInvited) {
                  return;
                }
                this.isInvited = true
                wx.showModal({
                  title: '温馨提示',
                  showCancel: false,
                  content: '您的服务医生已接诊，请您点击下方确认按钮进入问诊室进行视频问诊',
                  success: (e) => {
                    if (e.confirm) {
                      wx.reLaunch({
                        url: `/pages/chat/user_chat/user_chat?logId=${res.logId}&imId=${doctorIM}&inquiryPatientId=${id}&log_type=${inquiryType}&doctorId=${doctorId}&doctorName=${doctorName}&myIM=${patientIM}`
                      });
                    }
                  }
                });
                return;
              }

              if (this.isInvited) {
                return;
              }
              this.isInvited = true
              wx.reLaunch({
                url: `/pages/chat/user_chat/user_chat?logId=${res.logId}&imId=${doctorIM}&inquiryPatientId=${id}&log_type=${inquiryType}&doctorId=${doctorId}&doctorName=${doctorName}&myIM=${patientIM}`
              });
            }
          } else if (res.packageType === 6) {
            if (JSON.parse($service.getStore('userInfo')).type === "D") {
              let app = getApp();
              app.globalData.ullist = res.list;
              app.editTabBar();
            }
          } else if (res.packageType === 40) {
            if (JSON.parse($service.getStore('userInfo')).type !== "D") {
              let app = getApp();
              app.globalData.isRead = res.isRead;
              app.editTabBar1();
            }
          }
        }
      }
    });
  }

  sendWebSocketMsg(options) {
    if (!this.socketTask || !this.isConnect) {
      console.error('WebSocket未连接');
      return;
    }

    options.data.packageCode = 200;
    this.socketTask.send({
      data: JSON.stringify(options.data),
      success: (res) => {
        options.success?.(res);
      },
      fail: (err) => {
        options.fail?.(err);
      }
    });
  }

  closeWebSocket() {
    if (this.socketTask) {
      this.socketTask.close({
        success: () => {
          console.log('WebSocket已关闭');
        },
        fail: () => {
          console.log('WebSocket关闭失败');
        }
      });
    }
    this.isClosed = true;
    this.isConnect = false;
    this.socketTask = null;
  }

  reset() {
    clearInterval(this.timeoutObj);
    return this;
  }

  start() {
    this.timeoutObj = setInterval(() => {
      if (this.socketTask && this.isConnect) {
        this.socketTask.send({
          data: 'ping',
          success: () => {
            // console.log("心跳发送成功");
          },
          fail: (err) => {
            console.log(err);
            this.isConnect = false;
            if (!this.isClosed) {
              this.reConnect();
            }
            this.reset();
          }
        });
      }
    }, this.timeout);
  }

  reConnect() {
    console.log('正在重新连接WebSocket, 当前重连次数:', this.connectNum);
    if (this.connectNum < 3) {
      setTimeout(() => this.initWebSocket(), 3000);
    } else if (this.connectNum < 10) {
      setTimeout(() => this.initWebSocket(), 10000);
    } else {
      setTimeout(() => this.initWebSocket(), 450000);
    }
    this.connectNum++;
  }
}

// 创建实例
const websocket = new Websocket({
  heartCheck: true,
  isReconnection: true
});

export default websocket;
